// 导入音效文件
import bgmSound from '../assets/sounds/bgm.mp3';
import eatSound from '../assets/sounds/eat.mp3';
import moveSound from '../assets/sounds/move.mp3';
import dieSound from '../assets/sounds/die.mp3';


/**
 * @class SoundManager
 * @description 游戏音效管理器，负责管理所有游戏音效
 */
class SoundManager {
  /**
   * @type {Object.<string, HTMLAudioElement>}
   * @static
   */
  static sounds = {
    bgm: (() => {
        const audio = new Audio(bgmSound);
        audio.volume = 0.4;
        return audio;
    })(),
    eat: (() => {
        const audio = new Audio(eatSound);
        audio.volume = 0.6;
        return audio;
    })(),
    move: (() => {
        const audio = new Audio(moveSound);
        audio.volume = 0.3;
        return audio;
    })(),
    die: (() => {
        const audio = new Audio(dieSound);
        audio.volume = 0.7;
        return audio;
    })()
    };
    static settings = {
        bgmEnabled: true,
        soundEnabled: true
    };

    /**
     * 播放音效
     */
    static play(soundName) {
        if (!this.sounds[soundName]) return;
        
        // 根据音效类型判断是否播放
        if (soundName === 'bgm' && !this.settings.bgmEnabled) return;
        if (soundName !== 'bgm' && !this.settings.soundEnabled) return;

        const sound = this.sounds[soundName];
        sound.currentTime = 0;
        sound.play().catch(err => console.log(`${soundName} 播放失败:`, err));
    }

    /**
     * 循环播放
     */
    static loop(soundName) {
        if (!this.sounds[soundName]) return;
        
        // 背景音乐检查
        if (soundName === 'bgm' && !this.settings.bgmEnabled) return;

        const sound = this.sounds[soundName];
        sound.loop = true;
        sound.currentTime = 0;
        sound.play().catch(err => console.log(`${soundName} 循环播放失败:`, err));
    }

    /**
     * 停止指定音效
     */
    static stop(soundName) {
        if (!this.sounds[soundName]) return;
        const sound = this.sounds[soundName];
        sound.pause();
        sound.currentTime = 0;
    }

    /**
     * 切换背景音乐
     */
    static toggleBGM() {
        this.settings.bgmEnabled = !this.settings.bgmEnabled;
        if (!this.settings.bgmEnabled) {
            this.stop('bgm');
        } else if (this.sounds.bgm) {
            this.loop('bgm');
        }
        this.saveSettings();
    }

    /**
     * 切换音效
     */
    static toggleSound() {
        this.settings.soundEnabled = !this.settings.soundEnabled;
        this.saveSettings();
    }

    /**
     * 保存设置到本地存储
     */
    static saveSettings() {
        localStorage.setItem('snakeGameAudioSettings', JSON.stringify(this.settings));
    }

    /**
     * 加载设置
     */
    static loadSettings() {
        const saved = localStorage.getItem('snakeGameAudioSettings');
        if (saved) {
            this.settings = JSON.parse(saved);
        }
    }
}
// 初始化时加载设置
SoundManager.loadSettings();
export default SoundManager;